package com.pomr.service.sys.Impl;


import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.sys.AgencyDao;
import com.pomr.dao.sys.RoleDao;
import com.pomr.dao.sys.UserDao;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.Role;
import com.pomr.model.sys.User;
import com.pomr.service.sys.UserService;
import com.pomr.util.common.MD5;
import com.pomr.util.page.Page;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	@Qualifier("userDaoImpl")
	private UserDao userDao;
	@Autowired
	@Qualifier("agencyDaoImpl")
	private AgencyDao agencyDao;
	@Autowired
	@Qualifier("roleDaoImpl")
	private RoleDao roleDao;

	@Override
	public List<Agency> findAgencysWithUser(User user) throws Exception {
		int type = user.getRole().getId();
		
		List<Agency> agencys = null;
		//超级管理员--获取所有的机构信息 机构管理员用户只能获取本机构信息 普通用户不能创建用户无法获取机构信息
		if(type == 1){
			agencys = agencyDao.findByHql("from Agency where (status !='1' or status=null)");
		}else if(type == 4){
			
		}else{
			agencys = agencyDao.findByHql("from Agency where (status !='1' or status=null) and id = (select agency.id from user where id="+user.getId()+")");
		}
		return agencys;
	}

	@Override
	public boolean testUser(String uname) throws Exception {
		List<User> users = userDao.findByHql("from User where uname = '"+uname+"'");
		if(users == null || users.size()<=0){
			return false;
		}else{
			return true;
		}
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public boolean insertUser(User user) throws Exception {
		if(user.getPassword()==null || user.getPassword().equals("")){
			//默认密码12345678
			user.setPassword("12345678");
		}
		//对密码加密
		user.setPassword(MD5.encodeByMd5(user.getPassword()));
		user.setStatus("0");
		user.setCreateTime(new Date());
		int num = userDao.addNumKey(user);
		if(num <= 0){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public List<Role> findRolesWithUser(User user) throws Exception {
		return roleDao.findByHql("from Role where status=null or status!=-1 ");
	}

	@Override
	public Page<List<User>> findUsers(User user,String page) throws Exception {
		String hql = "from User where ";
		StringBuilder sb = new StringBuilder();
		if(user.getUname() !=null && !"".equals(user.getUname())){
			sb.append("and uname = '"+user.getUname()+"' ");
		}
		if(user.getName() !=null && !"".equals(user.getName())){
			sb.append("and name = '"+user.getName()+"' ");
		}
		if(user.getAgency().getId().intValue()>0){
			sb.append("and agency.id = "+user.getAgency().getId()+" ");
		}
		if(user.getRole().getId()>0){
			sb.append("and role.id = "+user.getRole().getId()+" ");
		}
		String str = sb.toString();
		if(str == null || str.equals("")){
			hql = "from User";
		}else{
			hql += str.replaceFirst("and ", "");
		}
		
		Page<List<User>> p = new Page<List<User>>();
		if(page == null || page.equals("")){
			p.setCunrrentPage(1);
		}else{
			p.setCunrrentPage(Integer.valueOf(page));
		}
		p.setPageSize(10);
		return userDao.showPage(hql, "select count(1) "+hql, p);
	}
	
	@Override
	public Page<List<User>> findUsersInter(User user,Page<List<User>> page) throws Exception {
		String hql = "from User where ";
		StringBuilder sb = new StringBuilder();
		if(user.getUname() !=null && !"".equals(user.getUname())){
			sb.append("and uname = '"+user.getUname()+"' ");
		}
		if(user.getName() !=null && !"".equals(user.getName())){
			sb.append("and name like '%"+user.getName()+"%' ");
		}
		if(user.getTel() !=null && !"".equals(user.getTel())){
			sb.append("and tel = '"+user.getTel()+"' ");
		}
		if(user.getAgency()!=null && user.getAgency().getId()!=null && user.getAgency().getId().intValue()>0){
			sb.append("and agency.id = "+user.getAgency().getId()+" ");
		}
		if(user.getRole()!=null && user.getRole().getId()>0){
			sb.append("and role.id = "+user.getRole().getId()+" ");
		}
		if(user.getStatus()!=null && user.getStatus().equals("1")){//作废
			sb.append("and status = '1' ");
		}else{
			sb.append("and (status != '1' or status = null) ");
		}
		String str = sb.toString();
		if(str == null || str.equals("")){
			hql = "from User";
		}else{
			hql += str.replaceFirst("and ", "");
		}
		
		return userDao.showPage(hql, "select count(1) "+hql, page);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteUsersInter(List<String> ids) throws Exception {
		if(ids == null || ids.size()<=0){
			return false;
		}
		int len = ids.size();
		for(int i=0; i<len; i++){
			String hql = "delete from User where id="+ids.get(i);
			if(!userDao.editHql(hql)){
				throw new Exception("删除失败");
			}
		}
		return true;
	}

	@Override
	public User serachUser(User user) throws Exception {
		List<User> users = userDao.findByHql("from User where id="+user.getId());
		if(users==null || users.size()<=0){
			return null;
		}else{
			user = users.get(0);
			user.setPassword(MD5.decodeByMD5(user.getPassword()));
			return user;
		}
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editUser(User user) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("update User set ");
		sb.append("name = '"+(user.getName()==null?"":user.getName())+"', ");
		sb.append("password = '"+MD5.encodeByMd5(user.getPassword())+"', ");
		sb.append("addr = '"+(user.getAddr()==null?"":user.getAddr())+"', ");
		sb.append("tel = '"+(user.getTel()==null?"":user.getTel())+"', ");
		sb.append("email = '"+(user.getEmail()==null?"":user.getEmail())+"', ");
		sb.append("status = '"+(user.getStatus()==null?"":user.getStatus())+"' ");
		sb.append("where uname='"+(user.getUname()==null?"":user.getUname())+"'");
		System.out.println(sb.toString());
		return userDao.editHql(sb.toString());
	}
	
	/**
	 * 获取机构下的用户
	 */
	public List<User> searchUsersOfAgency(User user) throws Exception{
		return userDao.findByHql("from User u1 where u1.agency.id = "+user.getAgency().getId()+" and (u1.status=null or u1.status != '1')");
	}

	@Override
	public List<User> searchUsersByAgency(Agency agency) throws Exception {
		return userDao.findByHql("from User u1 where u1.agency.id ="+agency.getId()+" and (u1.status=null or u1.status != '1')");
	}

	@Override
	public Page<List<User>> findUsersByCond(String page, String limit, Map<String, String> map) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from User where 1=1 ");
		String uname = map.get("uname");
		if(uname!=null && !uname.equals("")){
			sb.append("and uname like '%"+uname+"%' ");
		}
		String patientId = map.get("patientId");
		if(patientId!=null && !patientId.equals("")){
			String xa = map.get("xa");
			if(xa.equals("0")){//包含下属机构
				String hql = "from Agency where id="+patientId;
				Agency ag = (Agency) agencyDao.findByHql(hql).get(0);
				sb.append(" and agency.identifier like '"+ag.getIdentifier()+"%'");
			}else{
				sb.append(" and agency.id="+patientId);
			}
		}
		String status = map.get("status");
		if(status!=null && !status.equals("")){
			if(status.equals("0")){	
				
			}else if(status.equals("1")){
				sb.append(" and (status=null or status!='1')");
			}else{
				sb.append(" and (status='1')");
			}
		}
		sb.append(" order by id");
		Page<List<User>> p = new Page<List<User>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		return userDao.showPage(sb.toString(), "select count(1) "+sb.toString(), p);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editUserBase(User user) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("update User set ");
		sb.append(" name='"+user.getName()+"',");
		sb.append(" tel='"+user.getTel()+"',");
		sb.append(" email='"+user.getEmail()+"'");
		sb.append(" where id="+user.getId());
		return userDao.editHql(sb.toString());
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editUserStatus(User user) throws Exception {
		String hql = "update User set status = '"+user.getStatus()+"' where id="+user.getId();
		return userDao.editHql(hql);
	}

	@Override
	public boolean updatePwd(User user) throws Exception {
		if(user.getId()==null){
			return false;
		}
		if(user.getPassword()==null || user.getPassword().equals("")){
			user.setPassword("12345678");
		}
		//对密码加密
		String hql = "update User set password ='"+MD5.encodeByMd5(user.getPassword())+"' where id="+user.getId();
		return userDao.editHql(hql);
	}
}
